package cn.bud.msgbus.core.config;

import org.springframework.aop.interceptor.AsyncExecutionAspectSupport;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Service层添加注解@EnableAsync
 * Application启动类添加注解@EnableAsync
 * 使用自定义的需要声明@Async的name值
 * @author hxj
 */
//@EnableAsync
//@Configuration
public class ThreadPoolConfig {

    @Value("${general.thread-pool.core-size:10}")
    private Integer coreSize;
    @Value("${general.thread-pool.max-size:30}")
    private Integer maxSize;
    @Value("${general.thread-pool.capacity:100}")
    private Integer capacity;
    @Value("${general.thread-pool.Keep-alive-seconds:60}")
    private Integer keepAliveSeconds;
    @Value("${general.thread-pool.thread-name-prefix:generalTaskExecutor-}")
    private String threadNamePrefix;

    public static final String POOL_NAME = AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME;

    @PostConstruct
    @Bean(name = POOL_NAME)
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(coreSize);
        //最大线程数
        executor.setMaxPoolSize(maxSize);
        //队列容量
        executor.setQueueCapacity(capacity);
        //活跃时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //线程名字前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        // 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 线程池对拒绝任务的处理策略,当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；如果执行程序已关闭，则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
    
//    @Bean("taskExecutor")
//    public Executor taskExecutor() {
//        // 创建一个线程池对象
//        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
//        // 定义一个线程池大小
//        scheduler.setPoolSize(100);
//        // 线程池名的前缀
//        scheduler.setThreadNamePrefix("generalTaskExecutor-");
//        // 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
//        scheduler.setWaitForTasksToCompleteOnShutdown(true);
//        // 设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住
//        scheduler.setAwaitTerminationSeconds(60);
//        // 线程池对拒绝任务的处理策略,当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；如果执行程序已关闭，则会丢弃该任务
//        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        return scheduler;
//    }

}
